import React, { useState } from 'react';

import SvgIcon from '@/components/SvgIcon';

import { useAIApi } from '../../hooks/useAIApi';
import { useAudioRecorder } from '../../hooks/useAudio/index';
import { AudioControls, AudioFileList } from '../AudioRecorder/index';

interface VideoRecommendationTabProps {
	infoList: string;
	displayedText: string;
	onAudioResult: (result: string) => void;
	// 全局状态
	extractedTags?: string[];
	matchedVideos?: any[];
	isLoading?: boolean;
	transcriptionText?: string;
	audioState?: {
		fileList: File[];
		recordFile: Blob | null;
		playInfo: {
			localPlay: boolean;
			currentTime: number;
			duration: number;
		};
	};
	onStateChange: (state: any) => void;
}

// 定义标签类型
interface TagDefinition {
	id: string;
	name: string;
	description: string;
}

// 定义视频类型
interface VideoItem {
	id: number;
	title: string;
	tags: string[];
}

// 标签定义
const tagDefinitions: TagDefinition[] = [
	{ id: 'A', name: '日常养护与用车技巧', description: '关于车辆日常养护和使用技巧的内容' },
	{ id: 'B', name: '日常检查技巧', description: '关于车辆日常检查的技巧和方法' },
	{ id: 'C', name: '车型标签：问界 M7', description: '特定针对问界 M7 车型的内容' },
	{ id: 'D', name: '时长标签：短频', description: '时长较短的视频内容' },
	{ id: 'E', name: '增值服务：车主权益说明', description: '关于车主权益和增值服务的说明' },
	{ id: 'F', name: '功能教学：鸿蒙座舱操作', description: '关于鸿蒙座舱系统操作的教学内容' }
];

// 模拟视频数据
const mockVideos: VideoItem[] = [
	{ id: 1, title: '日常车辆保养全攻略', tags: ['A'] },
	{ id: 2, title: '问界M7车主必看的保养技巧', tags: ['A', 'C'] },
	{ id: 3, title: '如何正确检查车辆油液', tags: ['B'] },
	{ id: 4, title: '问界M7日常检查要点', tags: ['B', 'C'] },
	{ id: 5, title: '问界M7车型特点详解', tags: ['C'] },
	{ id: 6, title: '一分钟了解车辆状态', tags: ['B', 'D'] },
	{ id: 7, title: '快速掌握车辆保养知识', tags: ['A', 'D'] },
	{ id: 8, title: '车主权益与保障详解', tags: ['E'] },
	{ id: 9, title: '问界M7车主专享服务', tags: ['C', 'E'] },
	{ id: 10, title: '鸿蒙座舱功能介绍', tags: ['F'] },
	{ id: 11, title: '问界M7鸿蒙系统操作指南', tags: ['C', 'F'] },
	{ id: 12, title: '30秒掌握鸿蒙座舱核心功能', tags: ['D', 'F'] },
	{ id: 13, title: '车辆保养与检查全流程', tags: ['A', 'B'] },
	{ id: 14, title: '问界M7车主权益与服务', tags: ['C', 'E'] },
	{ id: 15, title: '鸿蒙座舱与车辆保养指南', tags: ['A', 'F'] },
	{ id: 16, title: '短视频：日常用车小技巧', tags: ['A', 'D'] },
	{ id: 17, title: '问界M7鸿蒙系统快速上手', tags: ['C', 'D', 'F'] },
	{ id: 18, title: '车主权益与鸿蒙座舱使用', tags: ['E', 'F'] }
];

// 模拟API接口返回标签
interface ApiTagResponse {
	success: boolean;
	data: string[];
	message?: string;
}

const BtnList = [
	{ title: '全文转录', type: 1 },
	{ title: '智能纪要提取', type: 2 },
	{ title: '在线编辑', type: 3 }
];

const VideoRecommendationTab: React.FC<VideoRecommendationTabProps> = ({
	infoList,
	displayedText,
	onAudioResult,
	extractedTags: propExtractedTags = [],
	matchedVideos: propMatchedVideos = [],
	isLoading: propIsLoading = false,
	transcriptionText: propTranscriptionText = '',
	audioState,
	onStateChange
}) => {
	const audioRecorder = useAudioRecorder();
	const { callQwen3API } = useAIApi();
	const [localExtractedTags, setLocalExtractedTags] = useState<string[]>(propExtractedTags);
	const [isProcessing, setIsProcessing] = useState(propIsLoading);

	// 使用props或本地状态
	const extractedTags = propExtractedTags.length > 0 ? propExtractedTags : localExtractedTags;

	// 同步全局状态的isLoading到本地isProcessing
	React.useEffect(() => {
		setIsProcessing(propIsLoading);
	}, [propIsLoading]);

	// 保存音频状态到全局状态
	React.useEffect(() => {
		// 当音频文件列表或录音文件变化时，更新全局状态
		if (audioRecorder.fileList.length > 0 || audioRecorder.recordFile) {
			onStateChange({
				audioState: {
					fileList: audioRecorder.fileList,
					recordFile: audioRecorder.recordFile,
					playInfo: audioRecorder.playInfo
				}
			});
		}
	}, [audioRecorder.fileList, audioRecorder.recordFile, audioRecorder.playInfo]);

	// 从props恢复音频状态
	React.useEffect(() => {
		if (audioState) {
			// 恢复文件列表
			if (audioState.fileList?.length > 0 && audioRecorder.fileList.length === 0) {
				audioRecorder.setFileList(audioState.fileList);
			}

			// 恢复录音文件
			if (audioState.recordFile && !audioRecorder.recordFile) {
				audioRecorder.setRecordFile(audioState.recordFile);
			}

			// 恢复播放信息
			if (audioState.playInfo) {
				audioRecorder.setPlayInfo(audioState.playInfo);
			}
		}
	}, [audioState]);

	// 处理录音开始
	const handleStartRecording = async () => {
		try {
			const stopFn = await audioRecorder.handleRecordVoice(onAudioResult);
			if (stopFn) {
				audioRecorder.setStopRecording(() => stopFn);
				audioRecorder.setIsRecording(true);
			}
		} catch (error) {
			console.error('录音控制错误:', error);
			audioRecorder.setError('录音控制失败');
			audioRecorder.setIsRecording(false);
		}
	};

	// 处理录音停止
	const handleStopRecording = () => {
		if (audioRecorder.stopRecording) {
			audioRecorder.stopRecording();
		}
		audioRecorder.setIsRecording(false);
	};

	// 处理文件上传
	const handleFileUpload = () => {
		audioRecorder.handleUploadVoice();
	};

	// 处理文件改变
	const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		audioRecorder.handleFileChange(e, onAudioResult);
	};

	// 处理删除文件
	const handleRemoveFile = (file: File) => {
		audioRecorder.setFileList(
			audioRecorder.fileList.filter(vv => vv.lastModified !== file.lastModified)
		);
		if (audioRecorder.playInfo.localPlay) {
			audioRecorder.pauseVoice();
			audioRecorder.setPlayInfo({
				...audioRecorder.playInfo,
				localPlay: false
			});
		}
	};

	// 模拟API调用获取标签
	const fetchTagsFromApi = async (text: string): Promise<ApiTagResponse> => {
		// 这里是模拟API调用，实际项目中应替换为真实的API调用
		setIsProcessing(true);

		try {
			// 构建提示词，要求AI从文本中提取相关标签
			const prompt = `
				请从以下文本中提取相关的标签，只返回标签ID（A-F）：
				A: 日常养护与用车技巧
				B: 日常检查技巧
				C: 车型标签：问界 M7
				D: 时长标签：短频
				E: 增值服务：车主权益说明
				F: 功能教学：鸿蒙座舱操作

				文本内容：${text}

				请以JSON格式返回提取的标签，格式为：{"tags": ["A", "C", "F"]}，只返回标签字母，不要返回标签的具体内容。
			`;

			// 修正参数顺序：prompt应该是第一个参数，text是提示词的一部分
			const response = await callQwen3API(prompt);

			// 增强API处理逻辑
			if (response?.choices?.[0]?.message?.content) {
				const content = response.choices[0].message.content;

				try {
					// 方法1：尝试解析完整的JSON对象
					const jsonMatch = content.match(/\{.*\}/s);
					if (jsonMatch) {
						const jsonData = JSON.parse(jsonMatch[0]);
						if (jsonData.tags && Array.isArray(jsonData.tags)) {
							const validTags = jsonData.tags.filter(
								(tag: string) => typeof tag === 'string' && /^[A-F]$/.test(tag)
							);
							if (validTags.length > 0) {
								return { success: true, data: validTags };
							}
						}
					}

					// 方法2：尝试解析JSON数组
					const arrayMatch = content.match(/\[.*\]/s);
					if (arrayMatch) {
						const arrayData = JSON.parse(arrayMatch[0]);
						if (Array.isArray(arrayData)) {
							const validTags = arrayData.filter(
								(tag: any) => typeof tag === 'string' && /^[A-F]$/.test(tag)
							);
							if (validTags.length > 0) {
								return { success: true, data: validTags };
							}
						}
					}

					// 方法3：使用正则表达式提取A-F的标签
					const tagMatches = content.match(/[A-F]/g);
					if (tagMatches && tagMatches.length > 0) {
						// 去重
						return { success: true, data: [...new Set(tagMatches)] };
					}

					// 如果以上方法都失败，尝试查找引号中的单个字母
					const quotedLetters = content.match(/"([A-F])"/g);
					if (quotedLetters && quotedLetters.length > 0) {
						const extractedTags = quotedLetters.map(match => match.replace(/"/g, ''));
						return { success: true, data: [...new Set(extractedTags)] };
					}

					// 最后尝试查找冒号后的单个字母
					const colonLetters = content.match(/:\s*([A-F])/g);
					if (colonLetters && colonLetters.length > 0) {
						const extractedTags = colonLetters.map(match => match.replace(/:\s*/, ''));
						return { success: true, data: [...new Set(extractedTags)] };
					}
				} catch (parseError) {
					console.error('解析标签JSON失败:', parseError);
					// 即使JSON解析失败，仍然尝试提取标签
					const tagMatches = content.match(/[A-F]/g);
					if (tagMatches && tagMatches.length > 0) {
						return { success: true, data: [...new Set(tagMatches)] };
					}
				}
			}

			console.warn('无法从API响应中提取标签');
			return { success: false, data: [], message: '无法从文本中提取标签' };
		} catch (error) {
			console.error('API调用失败:', error);
			return { success: false, data: [], message: '标签API调用失败' };
		} finally {
			setIsProcessing(false);
		}
	};

	// 从转写文本中提取标签
	const extractTagsFromText = async () => {
		if (!displayedText || isProcessing) return;

		try {
			setIsProcessing(true);
			onStateChange({
				isLoading: true,
				transcriptionText: displayedText,
				extractedTags: extractedTags,
				matchedVideos: filteredVideos
			});

			const response = await fetchTagsFromApi(displayedText);
			if (response.success && response.data.length > 0) {
				const newTags = response.data;
				setLocalExtractedTags(newTags);

				// 更新全局状态
				const newFilteredVideos = mockVideos.filter(video =>
					newTags.some(tag => video.tags.includes(tag))
				);

				onStateChange({
					isLoading: false,
					transcriptionText: displayedText,
					extractedTags: newTags,
					matchedVideos: newFilteredVideos
				});
			} else {
				console.error('获取标签失败:', response.message || '未能提取到有效标签');
				// 如果没有提取到标签，尝试使用默认标签
				const defaultTags = ['A', 'C']; // 默认使用日常养护和问界M7标签
				setLocalExtractedTags(defaultTags);

				const defaultVideos = mockVideos.filter(video =>
					defaultTags.some(tag => video.tags.includes(tag))
				);

				onStateChange({
					isLoading: false,
					transcriptionText: displayedText,
					extractedTags: defaultTags,
					matchedVideos: defaultVideos
				});

				// 显示友好提示
				message.info('未能精确提取标签，已使用默认推荐');
			}
		} catch (error) {
			console.error('提取标签失败:', error);
			// 出错时也使用默认标签
			const fallbackTags = ['A'];
			setLocalExtractedTags(fallbackTags);

			const fallbackVideos = mockVideos.filter(video =>
				fallbackTags.some(tag => video.tags.includes(tag))
			);

			onStateChange({
				isLoading: false,
				transcriptionText: displayedText,
				extractedTags: fallbackTags,
				matchedVideos: fallbackVideos
			});

			message.error('提取标签时出错，已显示默认推荐');
		}
	};

	// 根据提取的标签过滤视频
	const filteredVideos =
		propMatchedVideos.length > 0
			? propMatchedVideos
			: extractedTags.length > 0
				? mockVideos.filter(video => extractedTags.some(tag => video.tags.includes(tag)))
				: [];

	return (
		<div className="flex-col flex-1 px-8 relative">
			{/* 隐藏的文件输入 */}
			<input
				type="file"
				accept="audio/*"
				ref={audioRecorder.fileInputRef}
				onChange={handleFileChange}
				style={{ display: 'none' }}
			/>

			<div className="w-full text-5 pb-1 pt-8">请上传音频文件文件</div>

			{/* 音频文件列表 */}
			<AudioFileList
				fileList={audioRecorder.fileList}
				recordFile={audioRecorder.recordFile}
				playInfo={audioRecorder.playInfo}
				onPlayUploadRecord={audioRecorder.handlePlayUploadRecord}
				onPlayRecord={audioRecorder.handlePlayRecord}
				onRemoveFile={handleRemoveFile}
				onRemoveRecord={audioRecorder.handleRemoveRecord}
				onPauseVoice={audioRecorder.pauseVoice}
			/>

			{/* 功能按钮 */}
			{infoList.length === 0 && (
				<>
					<div className="color-[#333] text-6 pt-6">您希望：</div>
					<div className="w-full grid grid-cols-4 gap-4 pt-6">
						{BtnList.map((item, index) => {
							return (
								<div
									key={index}
									className="flex-center text-3.5 rounded-1 col-span-1 flex flex-col items-center bg-[#EDF6FF] color-[#56585B] h-10"
								>
									{item.title}
								</div>
							);
						})}
					</div>
				</>
			)}

			{/* 转录结果显示 */}
			<div className={`content ${displayedText ? 'h-[220px]' : 'flex-1'} py-6 overflow-auto`}>
				{displayedText && (
					<>
						<div className="text-4.5 color-[#333] lh-8">{`转录结果：`}</div>
						<div className="bg-gray-100 p-4 rounded-lg min-h-[100px]">{displayedText}</div>
						<button
							onClick={extractTagsFromText}
							disabled={isProcessing}
							className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400"
						>
							{isProcessing ? '处理中...' : '提取标签并推荐视频'}
						</button>
					</>
				)}
			</div>

			{/* 视频推荐区域 */}
			{extractedTags.length > 0 && (
				<div className="mt-4">
					<div className="text-4.5 color-[#333] lh-8 mb-2">提取的标签：</div>
					<div className="flex flex-wrap gap-2 mb-4">
						{extractedTags.map(tag => {
							const tagDef = tagDefinitions.find(t => t.id === tag);
							return (
								<div key={tag} className="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-sm">
									{tag}: {tagDef?.name || '未知标签'}
								</div>
							);
						})}
					</div>

					<div className="text-4.5 color-[#333] lh-8 mb-4">推荐视频：</div>
					<div className="grid grid-cols-3 gap-6 pb-6">
						{filteredVideos.map(video => (
							<div
								key={video.id}
								className="border border-gray-200 rounded-lg shadow-sm hover:shadow-md transition-shadow duration-300 overflow-hidden flex flex-col"
							>
								{/* 视频缩略图区域 */}
								<div className="bg-black h-32 flex items-center justify-center">
									<SvgIcon
										name="video-play"
										className="w-12 h-12 text-white opacity-70 hover:opacity-100 transition-opacity"
									/>
								</div>

								{/* 视频标题区域 */}
								<div className="p-4 flex-1">
									<div className="text-gray-700 font-medium text-lg mb-3 line-clamp-2 h-14">
										{video.title}
									</div>

									{/* 标签区域 */}
									<div className="flex flex-wrap gap-2">
										{video.tags.map(tag => {
											const tagDef = tagDefinitions.find(t => t.id === tag);
											const getTagColor = (tagId: string) => {
												const colors: Record<string, { bg: string; text: string }> = {
													A: { bg: 'bg-blue-50', text: 'text-blue-600' },
													B: { bg: 'bg-green-50', text: 'text-green-600' },
													C: { bg: 'bg-purple-50', text: 'text-purple-600' },
													D: { bg: 'bg-amber-50', text: 'text-amber-600' },
													E: { bg: 'bg-rose-50', text: 'text-rose-600' },
													F: { bg: 'bg-cyan-50', text: 'text-cyan-600' }
												};
												return colors[tagId] || { bg: 'bg-gray-50', text: 'text-gray-600' };
											};

											const { bg, text } = getTagColor(tag);

											return (
												<div
													key={tag}
													className={`px-2 py-1 ${bg} ${text} rounded-md text-xs font-medium`}
													title={tagDef?.name || ''}
												>
													{tag}
												</div>
											);
										})}
									</div>
								</div>

								{/* 操作区域 */}
								<div className="px-4 py-3 bg-gray-50 border-t border-gray-100 flex justify-between items-center">
									<span className="text-xs text-gray-500">推荐指数: {video.tags.length * 20}%</span>
									<button className="text-xs px-3 py-1 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors">
										查看详情
									</button>
								</div>
							</div>
						))}
					</div>
				</div>
			)}

			{/* 音频控制按钮 */}
			<AudioControls
				isRecording={audioRecorder.isRecording}
				onStartRecording={handleStartRecording}
				onStopRecording={handleStopRecording}
				onUploadFile={handleFileUpload}
			/>
		</div>
	);
};

export default VideoRecommendationTab;
